<template>
  <div class="exam-list-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>考试列表</span>
          <!-- 学生: 班级选择器 -->
          <el-select 
            v-if="isStudent" 
            v-model="selectedClassId" 
            placeholder="请选择班级以查看考试" 
            @change="handleClassChange" 
            clearable
            style="margin-left: 20px; width: 250px;"
            :loading="isClassLoading"
          >
            <el-option
              v-for="item in studentClasses"
              :key="item.id"
              :label="item.name"
              :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">ID:{{ item.id }}</span>
            </el-option>
          </el-select>
          <!-- 教师/管理员: 创建按钮 -->
          <el-button 
            v-if="canCreateExam" 
            type="primary" 
            :icon="Plus" 
            @click="goToCreateExam"
            style="margin-left: auto;"
          >
            创建考试
          </el-button>
        </div>
      </template>

      <el-empty description="请先选择一个班级来查看考试" v-if="isStudent && !selectedClassId"></el-empty>
      
      <!-- 考试表格 (仅在非学生或学生已选班级时显示) -->
      <el-table :data="exams" v-loading="isLoading" style="width: 100%" v-else>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="title" label="考试名称" min-width="150"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="200"></el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
           <template #default="{ row }">
            {{ formatDateTime(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长(分钟)" width="100"></el-table-column>
        <el-table-column prop="totalScore" label="总分" width="80"></el-table-column>
        <el-table-column prop="passScore" label="及格分" width="80"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="viewDetails(row.id)">详情</el-button>
            
            <!-- 学生操作 (enterExam 使用 selectedClassId) -->
            <el-button 
              v-if="isStudent && row.status === 'PUBLISHED'" 
              type="success" 
              link 
              size="small" 
              @click="enterExam(row.id)"
              :disabled="isExamTimePassed(row.endTime) || isExamTimeNotReached(row.startTime)"
            >
              进入考试
            </el-button>
            <el-button 
              v-if="isStudent && row.status === 'IN_PROGRESS'" 
              type="warning" 
              link 
              size="small" 
              @click="enterExam(row.id)"
              :disabled="isExamTimePassed(row.endTime)"
            >
              继续考试
            </el-button>
             <el-button 
              v-if="isStudent && row.status === 'ENDED' && row.showResults" 
              type="info" 
              link 
              size="small" 
              @click="viewResults(row.id)"
            >
              查看结果
            </el-button>

            <!-- 教师/管理员操作 -->
             <el-button 
              v-if="isOwnerOrAdmin(row.creatorId) && row.status === 'DRAFT'" 
              type="success" 
              link 
              size="small" 
              @click="handlePublishExam(row.id)"
            >
              发布
            </el-button>
             <el-button 
              v-if="isOwnerOrAdmin(row.creatorId) && row.status === 'PUBLISHED'" 
              type="warning" 
              link 
              size="small" 
              @click="handleStartExam(row.id)"
               :disabled="isExamTimeNotReached(row.startTime)" 
            >
              开始
            </el-button>
             <el-button 
              v-if="isOwnerOrAdmin(row.creatorId) && row.status === 'IN_PROGRESS'" 
              type="danger" 
              link 
              size="small" 
              @click="handleEndExam(row.id)"
            >
              结束
            </el-button>
             <el-button 
              v-if="isOwnerOrAdmin(row.creatorId) && row.status === 'DRAFT'" 
              type="primary" 
              link 
              size="small" 
              @click="editExam(row.id)"
            >
              编辑
            </el-button>
             <el-button 
              v-if="isOwnerOrAdmin(row.creatorId) && row.status !== 'IN_PROGRESS'" 
              type="danger" 
              link 
              size="small" 
              @click="handleDeleteExam(row.id)"
            >
              删除
            </el-button>
             <el-button 
              v-if="isOwnerOrAdmin(row.creatorId) && (row.status === 'ENDED' || row.status === 'MARKED')" 
              type="info" 
              link 
              size="small" 
              @click="goToRecords(row.id)"
             >
                查看提交/批改
             </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 可以添加分页控件 -->
       <el-pagination
        v-if="totalExams > 0 && (!isStudent || selectedClassId)"
        layout="prev, pager, next, total"
        :total="totalExams"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { getAllExams, getTeacherExams, getStudentExams, publishExam, startTeacherExam, endTeacherExam, deleteExam } from '@/services/examService';
import { getStudentClasses } from '@/services/classService';
import { ElMessage, ElTag, ElMessageBox, ElSelect, ElOption, ElEmpty } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const store = useStore();
const router = useRouter();

const exams = ref([]);
const isLoading = ref(false);
const totalExams = ref(0); // 用于分页
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示数量

// 学生相关的状态
const studentClasses = ref([]);
const selectedClassId = ref(null);
const isClassLoading = ref(false);

// 从 Vuex 获取用户角色和 ID 信息
const isAdmin = computed(() => store.getters.isAdmin);
const isTeacher = computed(() => store.getters.isTeacher);
const isStudent = computed(() => !isAdmin.value && !isTeacher.value && store.getters.isAuthenticated);
const currentUserId = computed(() => store.getters.getUserInfo?.id);

// 判断当前用户是否是该考试的创建者或者是管理员
const isOwnerOrAdmin = (creatorId) => {
    if (isAdmin.value) {
        return true; // 管理员总是有权限
    }
    // 检查是否为教师且是创建者
    const isMatch = isTeacher.value && currentUserId.value === creatorId;
    return isMatch; 
};

// 根据角色判断是否可以创建考试
const canCreateExam = computed(() => isTeacher.value || isAdmin.value);

// 获取学生班级列表 (学生专属)
const fetchStudentClasses = async () => {
    if (!isStudent.value) return;
    isClassLoading.value = true;
    try {
        const response = await getStudentClasses();
        if (response && response.success) {
            studentClasses.value = response.data || [];
        } else {
            studentClasses.value = [];
            // 错误已在 service 层提示
        }
    } catch (error) {
        console.error("Error fetching student classes:", error);
        ElMessage.error("加载班级列表失败");
        studentClasses.value = [];
    } finally {
        isClassLoading.value = false;
    }
};

// 获取考试列表数据 (根据角色和选择的班级调整)
const fetchExams = async () => {
  // 学生未选择班级时，不加载考试，并清空列表
  if (isStudent.value && !selectedClassId.value) {
    exams.value = [];
    totalExams.value = 0;
    return;
  }
  
  isLoading.value = true;
  let response;
  try {
    if (isAdmin.value) {
      response = await getAllExams();
    } else if (isTeacher.value) {
      response = await getTeacherExams();
    } else if (isStudent.value) {
      // 学生根据选择的 classId 获取考试
      response = await getStudentExams(selectedClassId.value);
    } else {
      ElMessage.warning('无法确定用户角色');
      isLoading.value = false;
      return;
    }

    if (response && response.success) {
      exams.value = response.data || [];
      totalExams.value = exams.value.length; 
    } else {
      exams.value = [];
      totalExams.value = 0;
      // 学生场景下，如果 service 返回错误，可能是班级无效或无权限，service 已提示
      // 非学生场景，service 也已提示
    }
  } catch (error) {
      console.error("Error fetching exams:", error);
      ElMessage.error("加载考试列表时发生未知错误");
      exams.value = [];
      totalExams.value = 0;
  } finally {
    isLoading.value = false;
  }
};

// 学生选择班级后的处理
const handleClassChange = (value) => {
  selectedClassId.value = value;
  currentPage.value = 1; // 切换班级后重置到第一页
  fetchExams(); // 重新获取选中班级的考试列表
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  // fetchExams(); // 分页逻辑保持不变 (如果后端支持分页则取消注释)
  ElMessage.info(`切换到第 ${page} 页 (前端分页模拟)`);
};

// 查看详情
const viewDetails = (id) => {
  router.push({ name: 'ExamDetail', params: { id } }); // 假设有 ExamDetail 路由
};

// 开始考试 (学生)
const enterExam = (examId) => {
  // 校验 selectedClassId 是否有效
  if (!selectedClassId.value) {
      console.error(`Error: Invalid selectedClassId (${selectedClassId.value}) when trying to enter exam ${examId}.`);
      ElMessage.error('请先选择一个有效的班级。');
      return; // 阻止导航
  }

  router.push({ 
      name: 'ExamTaking', 
      params: { id: examId },
      query: { classId: selectedClassId.value } // 使用当前选中的 classId
  });
};

// 编辑考试 (教师/管理员)
const editExam = (id) => {
  // 跳转到编辑页面
  router.push({ name: 'ExamEdit', params: { id } }); // 更新为跳转到 ExamEdit 路由
  // ElMessage.info(`准备编辑考试 ID: ${id} - 功能待实现`); // 移除旧提示
};

// 跳转到创建考试页面
const goToCreateExam = () => {
  router.push({ name: 'ExamCreate' });
}

// 新增：跳转到考试记录列表页面
const goToRecords = (examId) => {
    if (!examId) return;
    router.push({ name: 'ExamRecordsList', params: { id: examId } });
};

// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-';
  try {
    return new Date(dateTimeString).toLocaleString();
  } catch (e) {
    return dateTimeString; // 解析失败返回原始字符串
  }
};

// 获取状态文字
const getStatusText = (status) => {
  const map = {
    DRAFT: '草稿',
    PUBLISHED: '已发布',
    IN_PROGRESS: '进行中',
    ENDED: '已结束'
  };
  return map[status] || status;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    DRAFT: 'info',
    PUBLISHED: 'success',
    IN_PROGRESS: 'warning',
    ENDED: undefined
  };
  return map[status];
};

// 检查考试是否已过结束时间
const isExamTimePassed = (endTime) => {
  return endTime && new Date(endTime) < new Date();
};

// 检查考试是否还未到开始时间
const isExamTimeNotReached = (startTime) => {
   return startTime && new Date(startTime) > new Date();
}

// 处理发布考试
const handlePublishExam = async (id) => {
  try {
    await ElMessageBox.confirm('确定要发布这场考试吗？发布后部分信息将无法修改。', '确认发布', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    isLoading.value = true;
    const response = await publishExam(id);
    if (response && response.success) {
      ElMessage.success(response.message || '考试发布成功');
      fetchExams(); // 刷新列表
    } else {
       // 错误已在 service 层提示
    }
  } catch (error) {
    if (error !== 'cancel') {
        console.error('Publish exam error:', error);
        // ElMessage.error('发布操作失败'); // Service 层已提示
    }
  } finally {
      isLoading.value = false;
  }
};

// 处理开始考试
const handleStartExam = async (id) => {
   try {
    await ElMessageBox.confirm('确定要开始这场考试吗？学生将可以进入考试。', '确认开始', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    isLoading.value = true;
    const response = await startTeacherExam(id);
    if (response && response.success) {
      ElMessage.success(response.message || '考试已开始');
      fetchExams(); // 刷新列表
    } else {
       // 错误已在 service 层提示
    }
  } catch (error) {
     if (error !== 'cancel') {
        console.error('Start exam error:', error);
     }
  } finally {
      isLoading.value = false;
  }
};

// 处理结束考试
const handleEndExam = async (id) => {
   try {
    await ElMessageBox.confirm('确定要立即结束这场考试吗？所有未提交的答卷将自动提交。', '确认结束', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger',
    });
    isLoading.value = true;
    const response = await endTeacherExam(id);
    if (response && response.success) {
      ElMessage.success(response.message || '考试已结束');
      fetchExams(); // 刷新列表
    } else {
       // 错误已在 service 层提示
    }
  } catch (error) {
     if (error !== 'cancel') {
        console.error('End exam error:', error);
     }
  } finally {
      isLoading.value = false;
  }
};

// 处理删除考试
const handleDeleteExam = async (id) => {
   try {
    await ElMessageBox.confirm('确定要删除这场考试吗？此操作不可恢复。', '确认删除', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'error',
    });
    isLoading.value = true;
    const response = await deleteExam(id);
    if (response && response.success) {
      ElMessage.success(response.message || '考试删除成功');
      fetchExams(); // 刷新列表
    } else {
       // 如果后端返回失败，显示后端提供的消息，或者一个默认消息
       ElMessage.error(response?.message || '删除考试失败，请稍后重试'); 
    }
  } catch (error) {
     if (error !== 'cancel') {
        console.error('Delete exam error:', error);
     }
  } finally {
      isLoading.value = false;
  }
};

// 移除或注释掉旧的占位函数
// const startExam = (exam) => { ... };
// const continueExam = (exam) => { ... };
// eslint-disable-next-line no-unused-vars
const viewResults = (_id) => { /* ... 占位 ... */ };

// 组件挂载时获取数据
onMounted(() => {
  if (isStudent.value) {
    fetchStudentClasses(); // 学生加载班级列表
    // 学生不立即加载考试，等待选择班级
  } else {
    fetchExams(); // 教师或管理员直接加载考试列表
  }
});

</script>

<style scoped>
.exam-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 